//
//  WZLocationViewController.m
//  ETong
//
//  Created by wanzhao on 15/11/25.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZLocationViewController.h"
#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Map/BMKPolyline.h>
#import <BaiduMapAPI_Map/BMKPolylineView.h>
#import <BaiduMapAPI_Map/BMKPointAnnotation.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Location/BMKLocationService.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearch.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearchOption.h>
#import <BaiduMapAPI_Search/BMKRouteSearch.h>
#import <BaiduMapAPI_Search/BMKGeocodeSearchOption.h>
#import "MBProgressHUD+WZ.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "Masonry.h"


@interface WZLocationViewController ()<BMKMapViewDelegate, BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate, BMKRouteSearchDelegate>

@property (nonatomic, weak) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *service;
@property (nonatomic, strong) BMKGeoCodeSearch *search;
@property (nonatomic, strong) BMKUserLocation *userLocation;
@property (nonatomic, strong) BMKRouteSearch *driveSearch;
@property (nonatomic, copy) NSString *outPosition;
@property (nonatomic, copy) NSString *mylocation;

@end


@implementation WZLocationViewController

{
    BMKPointAnnotation* pointAnnotation;
    BMKPointAnnotation* animatedAnnotation;
}


- (void)dealloc
{
    _mapView.delegate = nil;
    _service.delegate = nil;
    _search.delegate = nil;
    
    
    if (_mapView) {
        _mapView = nil;
    }
    
    NSLog(@"WZLocationViewController  dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupMapView];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [self addPointAnnotation];
}

- (void)setupMapView {
    
    self.view.backgroundColor = WhiteColor;
    self.navigationItem.title = @"定位查看";
    
    BMKMapView *map = [[BMKMapView alloc] init];
    self.mapView = map;
    map.frame = self.view.bounds;
    map.delegate = self;
    map.zoomLevel = 15;
    map.mapType = BMKMapTypeStandard;
    map.showsUserLocation = NO;//先关闭显示的定位图层
    map.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    map.showsUserLocation = YES;//显示定位图层
    [self.view addSubview:map];
    [self addButton];
}


- (void)addButton {
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"backtobegin"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backToBegin) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mapView.mas_left).offset(20);
        make.bottom.equalTo(self.mapView.mas_bottom).offset(-80);
        make.width.height.mas_equalTo(40);
    }];
    
    
    UIButton *locBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [locBtn setBackgroundImage:[UIImage imageNamed:@"weizhi"] forState:UIControlStateNormal];
    [locBtn addTarget:self action:@selector(showRoute) forControlEvents:UIControlEventTouchUpInside];
    [self.mapView addSubview:locBtn];
    [locBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mapView.mas_right).offset(-20);
        make.bottom.equalTo(self.mapView.mas_bottom).offset(-80);
        make.width.height.mas_equalTo(40);
    }];
    
    locBtn.hidden = (self.outCoordiNate2D.longitude && self.outCoordiNate2D.latitude) ? NO : YES;
}

- (void)backToBegin {
    
    if (!_userLocation) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = @"定位中...";
        return;
    } else {
        
        BMKCoordinateRegion region = BMKCoordinateRegionMakeWithDistance(_userLocation.location.coordinate, 1000.0f, 1000.0f);
        [self.mapView setRegion:region animated:YES];
    }
}


- (void)showRoute {
    
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:self.userCoordiNate2D.latitude longitude:self.userCoordiNate2D.longitude];
    CLLocation *location2 = [[CLLocation alloc] initWithLatitude:self.outCoordiNate2D.latitude longitude:self.outCoordiNate2D.longitude];
    
    [self getOverlayPointWithFriendLocation:location1 AndMyLocation:location2];
}

- (void)showRouteWithOneLocation:(CLLocation *)oneLocation OtherLocation:(CLLocation *)otherLocation {
    
    [self getOverlayPointWithFriendLocation:oneLocation AndMyLocation:otherLocation];
}

- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
    
    if (mapView == _mapView) {
        
        [self setupLocationService];
    }
}

- (void)setupLocationService {
    
    _service = [[BMKLocationService alloc] init];
    _service.delegate = self;
    [_service startUserLocationService];
    [MBProgressHUD showMessage:@"定位中..." toView:self.mapView];
    
    _driveSearch = [[BMKRouteSearch alloc]init];
    _driveSearch.delegate = self;
    
    _search = [[BMKGeoCodeSearch alloc] init];
    _search.delegate = self;
    
    
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    [MBProgressHUD hideHUDForView:_mapView];
    _userLocation = userLocation;
    BMKCoordinateRegion region = BMKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 1000.0f, 1000.0f);
    [self.mapView setRegion:region animated:YES];
    [_service stopUserLocationService];
    _userLocation = userLocation;
    [self.mapView updateLocationData:userLocation];
    
    BMKReverseGeoCodeOption *option = [BMKReverseGeoCodeOption new];
    option.reverseGeoPoint = userLocation.location.coordinate;
    [_search reverseGeoCode:option];
}

- (void)addAnnotation:(BMKUserLocation*)userlocation {
    BMKPointAnnotation *annotation = [BMKPointAnnotation new];
    annotation.title =  self.mylocation;
    annotation.coordinate = userlocation.location.coordinate;
    [self.mapView addAnnotation:annotation];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
//    self.mylocation = result.address;
//    [self addAnnotation:_location];
    [self addPointAnnotation];
}

// 外出地址添加标注
- (void)addPointAnnotation {
    
    if (pointAnnotation == nil) {
        pointAnnotation = [[BMKPointAnnotation alloc]init];
        
        pointAnnotation.coordinate = self.outCoordiNate2D;
        pointAnnotation.title = self.wzout.customerName;
        pointAnnotation.subtitle = self.wzout.outAddress;
    }
    [self.mapView addAnnotation:pointAnnotation];
}



- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        //设置大头针在地图上是否可以拖动
        newAnnotationView.draggable = NO;
        [newAnnotationView setSelected:YES animated:YES];
        return newAnnotationView;
    }
    return nil;
}


-(void)getOverlayPointWithFriendLocation:(CLLocation*)friendLocation AndMyLocation:(CLLocation*)myLocation {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES].labelText = @"计算路线中...";
    BMKPlanNode *startNode = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D startCoordinate;
    startCoordinate.latitude =friendLocation.coordinate.latitude;
    startCoordinate.longitude =friendLocation.coordinate.longitude;
    startNode.pt = startCoordinate;
    BMKPlanNode *endNode = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D endCoordnate;
    endCoordnate.latitude = myLocation.coordinate.latitude;
    endCoordnate.longitude = myLocation.coordinate.longitude;
    endNode.pt = endCoordnate;
    BMKDrivingRoutePlanOption * drivingRoutePlanOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRoutePlanOption.from = startNode;
    drivingRoutePlanOption.to = endNode;
    [_driveSearch drivingSearch:drivingRoutePlanOption];
    BMKCoordinateRegion region ;
    CLLocationDegrees latitude;
    CLLocationDegrees longitude;
    BMKCoordinateSpan span;
    if (myLocation.coordinate.latitude > friendLocation.coordinate.latitude) {
        latitude =myLocation.coordinate.latitude -(myLocation.coordinate.latitude - friendLocation.coordinate.latitude)/2.0;
        span.latitudeDelta = myLocation.coordinate.latitude - friendLocation.coordinate.latitude;
    }
    else
    {
        latitude =friendLocation.coordinate.latitude -(friendLocation.coordinate.latitude - myLocation.coordinate.latitude)/2.0;
        span.latitudeDelta = friendLocation.coordinate.latitude - myLocation.coordinate.latitude;
    }
    if (myLocation.coordinate.longitude > friendLocation.coordinate.longitude) {
        longitude = myLocation.coordinate.longitude - (myLocation.coordinate.longitude - friendLocation.coordinate.longitude)/2.0;
        span.longitudeDelta = myLocation.coordinate.longitude - friendLocation.coordinate.longitude;
    }
    else
    {
        longitude = friendLocation.coordinate.longitude - (friendLocation.coordinate.longitude - myLocation.coordinate.longitude)/2.0;
        span.longitudeDelta = friendLocation.coordinate.longitude - myLocation.coordinate.longitude;
    }
    region.center = CLLocationCoordinate2DMake(latitude, longitude);
    region.span = span;
    [_mapView setRegion:region];
    [_mapView setZoomLevel:_mapView.zoomLevel-1];
}

//查找路线回调
-(void)onGetDrivingRouteResult:(BMKRouteSearch *)searcher result:(BMKDrivingRouteResult *)result errorCode:(BMKSearchErrorCode)error
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        NSInteger size = [plan.steps count];
        NSInteger planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep *transitStep = [plan.steps objectAtIndex:i];
            planPointCounts += transitStep.pointsCount;
        }
        BMKMapPoint *temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine];
        [MBProgressHUD hideHUDForView:_mapView];
        
    }
}

- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay {
    if ([overlay isKindOfClass:[BMKPolyline class]]){
        BMKPolylineView* polylineView = [[BMKPolylineView alloc]initWithOverlay:overlay];
        polylineView.strokeColor = WZRGBColor(86, 154, 252);
        polylineView.lineWidth = 5.0;
        return polylineView;
    }
    return nil;
}

@end

